//
//  WXPAuthFaceVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "WXPAuthFaceVC.h"
#import "WXPFaceScanBtn.h"
#import "WXPFaceErrorExampleView.h"
#import "WXPFaceCameraVC.h"
#import "WXPLivenessFailView.h"
#import "WXPWebLivenessVC.h"

@interface WXPAuthFaceVC ()

@property (nonatomic, strong) WXPFaceScanBtn * faceScanBtn;
@property (nonatomic, strong) WXPFaceErrorExampleView * errorExampleView;
@property (nonatomic, strong) WXPTextRemindView * remindView;
@property (nonatomic, assign) BOOL isHiddenRemindView;
@property (nonatomic, strong) WXPLivenessFailView * livenessFailView;

@property (nonatomic,   copy) NSString * photoName;
@property (nonatomic,   copy) NSString * livenessId;

@end

@implementation WXPAuthFaceVC

#pragma mark - lazy
- (WXPFaceScanBtn *)faceScanBtn
{
    if (_faceScanBtn == nil) {
        _faceScanBtn = [WXPFaceScanBtn new];
        WEAKSELF
        _faceScanBtn.blockAuth = ^{
            [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                if(granted){
                    [GlobalMethod mainQueueBlock:^{
                        [weakSelf requestCheckUserCanAuth];
                    }];
                }
            }];
        };
    }
    return  _faceScanBtn;
}
- (WXPFaceErrorExampleView *)errorExampleView{
    if (!_errorExampleView) {
        _errorExampleView = [WXPFaceErrorExampleView new];
    }
    return _errorExampleView;
}
- (WXPTextRemindView *)remindView{
    if (!_remindView) {
        _remindView = [WXPTextRemindView new];
        [_remindView resetViewWithContent:@"El éxito de reconocimiento facial le ayuda a conseguir una cuota más alta"];
        WEAKSELF
        _remindView.blockClose = ^{
            weakSelf.isHiddenRemindView = true;
            [weakSelf resetHeaderView];
        };
    }
    return _remindView;
}
- (WXPLivenessFailView *)livenessFailView
{
    if (_livenessFailView == nil) {
        _livenessFailView = [WXPLivenessFailView  new];
    }
    return  _livenessFailView;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyFacial featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyFacial featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navView resetViewWithTitle:@"Verificación Facial"];
    [self.progressView resetViewWithNum:@"2"];
    [self.progressView.moneyView resetViewWithTag:2];
    [self resetHeaderView];
    self.btnAuth.hidden = true;
    WEAKSELF
    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
        [NSObject clickFeedback];
        [weakSelf.btnAuth addClickAnimate];
        [weakSelf requestSubmitAuth];
    }];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.progressView,
        [GlobalMethod getViewWithHeight:16],
        self.faceScanBtn,
        [GlobalMethod getViewWithHeight:45],
        self.errorExampleView,
        [GlobalMethod getViewWithHeight:Ratio(18)],
        self.isHiddenRemindView ? [UIView new] : self.remindView,
        [GlobalMethod getViewWithHeight:LEFT_MARDIN*2],
        //[GlobalMethod getViewWithHeight:(SCREEN_HEIGHT-self.btnAuth.top)],
    ]];
    self.tableView.height = SCREEN_HEIGHT-[GlobalMethod getNavgationBarHeight]-LEFT_MARDIN;
    self.tableView.tableHeaderView = self.headerView;
}

#pragma mark - 跳转去活体认证
// 跳转去活体拍照
- (void)jumpToLivenessCamera{
    [GlobalMethod buryPointWithPageName:KEY_VerifyFacial featureName:KEY_Liveness_Click action:KEY_BUTTON_CLICK type:KEY_button];
    [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Liveness_Click extInfo:nil];
    WEAKSELF
    WXPFaceCameraVC * vc = [WXPFaceCameraVC new];
    vc.liveType = 2;
    vc.livenChannelEnum = KEY_SILENCE_LIVENESS;
    vc.liveTypeEnum = KEY_AUTH_LIVE;
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        [weakSelf uploadSuccessWithUrl:url photoName:photoName livenessId:livenessId];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [weakSelf uploadFailIsH5:false];
    };
    self.startTime = [GlobalMethod getTimeStampMillisecond];
    [Global_Nav pushViewController:vc animated:true];
}

// 跳转去H5活体拍照
- (void)jumpToLivenessH5{
    // 打点
    [GlobalMethod buryPointWithPageName:KEY_VerifyFacial featureName:KEY_Liveness_Click action:KEY_BUTTON_CLICK type:KEY_button];
    [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Liveness_Click extInfo:nil];
    WXPWebLivenessVC * vc = [WXPWebLivenessVC new];
    vc.liveTypeEnum = KEY_AUTH_LIVE;
    WEAKSELF
    vc.blockUploadSuccess = ^(NSString *url, NSString *photoName, NSString *livenessId) {
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_H5_Liveness_Sucess extInfo:nil];
        [weakSelf uploadSuccessWithUrl:url photoName:photoName livenessId:livenessId];
    };
    vc.blockUploadFail = ^(NSString * errorStr) {
        [weakSelf uploadFailIsH5:true];
    };
    [Global_Nav pushViewController:vc animated:true];
}

- (void)uploadSuccessWithUrl:(NSString *)url photoName:(NSString *)photoName livenessId:(NSString *)livenessId {
    self.livenessId = livenessId;
    // 显示图片
    if(isStr(url)){
        // [self.errorExampleView resetLivenessImageWithUrl:url];
        // 确认提交
        [self requestSubmit];
    }
    self.photoName = photoName;
}

- (void)uploadFailIsH5:(BOOL)isH5 {
//    self.errorExampleView.bigImg.hidden = false;
//    self.errorExampleView.livenessImage.hidden = true;
    if (isH5 == false) {
        [self.view addSubview:self.livenessFailView];
    }
}

#pragma mark - request
// 检查用户是否可以做某项授权
- (void)requestCheckUserCanAuth{
    [RequestApi requestCheckUserCanAuthWithType:KEY_LIVENESS phone: @"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if([response boolValueForKey:KEY_checkResult]){
            // true：调用获取活体渠道接口，根据返回的skipLiven执行不同的逻辑
            [self requestAuthLivenConfig];
        }else{
            // 当接口返回‘false’时，弹窗提示
            [GlobalMethod showAlert:@"Lo sentimos. Aún no es la fecha del evento"];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 获取活体渠道接口
- (void)requestAuthLivenConfig{
    [RequestApi requestNewAuthLivenConfigWithPhone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // response 返回：
        // SILENCE_LIVENESS = "1";
        // skipLiven = false;
        BOOL result = [response boolValueForKey:KEY_skipLiven];
        if(result){
            // true：需要进行一次保存，保存时data为空对象{}
            self.startTime = [GlobalMethod getTimeStampMillisecond];
            [self requestSaveUserInfo];
        }else{
            // false：根据返回的参数值进行判断
            if (isStr([response stringValueForKey:KEY_SILENCE_LIVENESS])){
                // SILENCE_LIVENESS不为null：跳转静默活体页开始做静默活体拍照
                // 先验证相机，验证成功再去拍照
                [GlobalMethod isOpenCamearPermissionsWithCompletion:^(BOOL granted) {
                    if(granted){
                        [GlobalMethod mainQueueBlock:^{
                            [self jumpToLivenessCamera];
                        }];
                    }
                }];
            }else if (isStr([response stringValueForKey:KEY_CLOUDUN_H5_V3])){
                // CLOUDUN_H5_V3不为null：跳转LivenessH5 SDK-2活体进行识别
                [self jumpToLivenessH5];
            }
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 保存用户信息
- (void)requestSaveUserInfo{
    [RequestApi requestSaveUserInfoWithData:@{} step:KEY_LIVENESS_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        //[GlobalMethod userBehaviorRecordWithPageName:@"VerifyFacial" action:@"Save_End" extInfo:nil];
        //[GlobalMethod showAlert:@"¡Verificación exitosa! "];
        // 等一秒钟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 风控
            [GlobalMethod addRiskControlWithType:KEY_LIVE_OCR startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
            // 获取下一步
            [self requestGetNextStep];
        });
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

- (void)requestSubmitAuth{
    
}

// 提交用户信息
- (void)requestSubmit{
    [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Save_Start extInfo:nil];
    NSDictionary * dic = @{
        KEY_liveImg: readStr(self.photoName),
        KEY_livenessId: readStr(self.livenessId),
    };
    [RequestApi requestSaveUserInfoWithData:dic step:KEY_LIVENESS_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Save_End extInfo:nil];
        [GlobalMethod showAlert:@"¡Verificación exitosa! "];
        
        // 风控
        [GlobalMethod addRiskControlWithType:KEY_LIVE_OCR startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        // 调用获取下一步接口，跳转到该接口返回的对应认证页面
        [self requestGetNextStep];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}





@end
